<template>
  <div>
    <el-form
      :inline="true"
      :model="formInline"
      class="demo-form-inline"
      style="margin: 20px 30px 0px"
    >
      <el-form-item>
        <el-button type="primary" @click="handleQuery()">查询</el-button>
        <el-button type="primary" @click="addDoc()">新增</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="level1"
      style="width: 100%"
      row-key="id"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column label="名称" width="300">
        <template #default="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>

      <el-table-column label="父文档" width="250">
        <template #default="scope">
          {{ scope.row.parent }}
        </template>
      </el-table-column>

      <el-table-column label="顺序" width="250">
        <template #default="scope">
          {{ scope.row.sort }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >&nbsp;&nbsp;
          <el-dialog
            title="文档表单"
            :width="500"
            v-model="dialogFormVisible"
            :modal="false"
          >
            <el-form :model="doc" v-loading="loading">
              <el-form-item label="名称" :label-width="formLabelWidth">
                <el-input v-model="doc.name" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="父文档" :label-width="formLabelWidth">
                <el-select v-model="doc.parent" placeholder="请选择">
                  <el-option value="0">无</el-option>
                  <el-option :label="selectTreeName" :value="doc.parent">
                    <el-tree
                      id="tree-option"
                      :data="treeSelectData"
                      :accordion="true"
                      :props="props"
                      :default-expand-all="true"
                      :expand-on-click-node="false"
                      node-key="id"
                      :default-expanded-keys="[]"
                      @node-click="handleNodeClick"
                    >
                    </el-tree>
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="顺序" :label-width="formLabelWidth">
                <el-input v-model="doc.sort" autocomplete="off"></el-input>
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleSave">确 认</el-button>
              </span>
            </template>
          </el-dialog>

          <el-popconfirm
            confirmButtonText="确认"
            cancelButtonText="取消"
            icon="el-icon-info"
            iconColor="red"
            title="删除后不可恢复，确认删除?"
            @confirm="handleDelete(scope.$index, scope.row)"
          >
            <template #reference>
              <el-button size="mini" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import axios from "axios";
import { ref, reactive } from "vue";
import { defineComponent } from "vue";
import { ElMessage } from "element-plus";
import Tool from "../../util/tool";
import {useRoute} from 'vue-router'
export default {
  name: "AdminDoc",
  data() {
    return {
      // 配置项
      props: {
        label: "name", // 显示名称
        children: "children", // 子级字段名
      },
      formLabelWidth: "120px",
      formComponentSize: "100px",
    };
  },
  setup() {
    console.log("组件初始化成功");
    const docs = ref();

    const formInline = ref();
    formInline.value = {};

    const level1 = ref();

    const treeSelectData = ref();
    treeSelectData.value = [];

    const doc = ref();
    const dialogFormVisible = ref(false);

    const selectTreeName = ref();

    const loading = ref(false);

    const route=useRoute()

    /**
     * 数据查询
     **/
    const handleQuery = () => {
      axios
        .get("/doc/all")
        .then(function (response) {
          const data = response.data;
          if (data.success) {
            docs.value = data.content;
            console.log("原始数组：", docs.value);

            level1.value = [];
            level1.value = Tool.array2Tree(docs.value, 0);
          } else {
            ElMessage.error(data.message);
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    };

    /**
     * 编辑
     */
    const handleEdit = (index, row) => {
      console.log("index:" + index);
      console.log("row", row);
      dialogFormVisible.value = true;
      doc.value = Tool.copy(row);

      //不能选择当前节点极其所有子孙节点，作为父节点，会使树断开
      console.log("level1=>", level1.value);
      treeSelectData.value = Tool.copy(level1.value);
      console.log("treeSelectData=>", treeSelectData.value);
      setDisable(treeSelectData.value, row.id);
    };

    /**
     * 添加
     */
    const addDoc = () => {
      dialogFormVisible.value = true;
      doc.value = {
        ebookId:route.query.ebookId
      };

      //不能选择当前节点极其所有子孙节点，作为父节点，会使树断开
      treeSelectData.value = Tool.copy(level1.value);
    };

    /**
     * 将某节点及其子孙节点全部置为disabled
     */
    const setDisable = (treeSelectData, id) => {
      // console.log(treeSelectData, id);
      // 遍历数组，即遍历某一层节点
      for (let i = 0; i < treeSelectData.length; i++) {
        const node = treeSelectData[i];
        if (node.id === id) {
          // 如果当前节点就是目标节点
          console.log("disabled=>", node);
          // 将目标节点设置为disabled
          node.disabled = true;
          console.log("disabled2=>", node);
          // 遍历所有子节点，将所有子节点全部都加上disabled
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            for (let j = 0; j < children.length; j++) {
              setDisable(children, children[j].id);
            }
          }
        } else {
          // 如果当前节点不是目标节点，则到其子节点再找找看。
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            setDisable(children, id);
          }
        }
      }
    };



    const ids=[]
     /**
     * 查找整根树枝
     */
    const getDeleteIds = (treeSelectData, id) => {
      // console.log(treeSelectData, id);
      // 遍历数组，即遍历某一层节点
      for (let i = 0; i < treeSelectData.length; i++) {
        const node = treeSelectData[i];
        if (node.id === id) {
          // 如果当前节点就是目标节点
          console.log("delete=>", node);
          // 将目标节点设置为disabled
          //node.disabled = true;
          //将目标ID放入结果集ids
          ids.push(id);
          // 遍历所有子节点，将所有子节点全部都加上disabled
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            for (let j = 0; j < children.length; j++) {
              getDeleteIds(children, children[j].id);
            }
          }
        } else {
          // 如果当前节点不是目标节点，则到其子节点再找找看。
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            getDeleteIds(children, id);
          }
        }
      }
    };

    /**
     * 删除
     */
    const handleDelete = (index, row) => {
      console.log("==========删除==========");
      console.log("index:" + index);
      console.log("row", row);
      getDeleteIds(level1.value,row.id)
      axios
        .delete("/doc/delete/" +ids.join(","))
        .then(function (response) {
          const data = response.data;
          if (data.success) {
            ElMessage.success({
              message: "操作成功！",
              type: "success",
            });
            //重新加载列表
            handleQuery();
          }
        })
        .catch(function (error) {
          ElMessage.error("操作失败！");
          console.log(error);
        });
    };

    /**
     * 保存
     */
    const handleSave = () => {
      loading.value = true;
        axios
        .post("/doc/save", doc.value)
        .then(function (response) {
          loading.value = false;
          const data = response.data;
          if (data.success) {
            ElMessage.success({
              message: "操作成功！",
              type: "success",
            });
           dialogFormVisible.value = false;

            //重新加载列表
           handleQuery();
          } else {
            ElMessage.error(data.message);
          }
        })
        .catch(function (error) {
          loading.value = false;
          dialogFormVisible.value = false;
          ElMessage.error("操作失败！");
          console.log(error);
        });
    };

    const handleNodeClick = (node) => {
      console.log("node=>", node);
      selectTreeName.value = node.name;
      doc.value.parent = node.id;
    };

    onMounted: {
      console.log("onMounted=>2222");
      handleQuery();
    }

    return {
      level1,
      //docs,
      handleQuery,
      formInline,
      handleEdit,
      addDoc,
      treeSelectData,
      doc,
      dialogFormVisible,
      selectTreeName,
      handleSave,
      loading,
      handleNodeClick,
      handleDelete,
      addDoc,
      handleEdit,
    };
  },
  methods: {
    onSubmit() {
      console.log("submit!");
    },
  },
};
</script>

<style lang="scss">
.el-scrollbar .el-scrollbar__view .el-select-dropdown__item {
  height: auto;
  max-height: 274px;
  padding: 0;
  overflow: hidden;
  overflow-y: auto;
}

::-webkit-scrollbar {
  width: 5px;
  background-color: #f3f3f3;
}

/* 滚动槽 */
::-webkit-scrollbar-track {
  border-radius: 10px;
}

/* 滚动条滑块 */
::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background: #1aa094;
}

.el-select-dropdown__item.selected {
  font-weight: normal;
}
ul li >>> .el-tree .el-tree-node__content {
  height: auto;
  padding: 0 20px;
}
.el-tree-node__label {
  font-weight: normal;
}
.el-tree >>> .is-current .el-tree-node__label {
  color: #409eff;
  font-weight: 700;
}
.el-tree >>> .is-current .el-tree-node__children .el-tree-node__label {
  color: #606266;
  font-weight: normal;
}
</style>
